class AddSaltedToUsers < ActiveRecord::Migration
  def self.up
    
    #self.remove_generator_password
    @old_users = User.find(:all)
    
    
    add_column 'users', :crypted_password, :string, :limit => 40
    add_column 'users', :salt, :string, :limit => 40
    
    begin
      @new_users = User.find(:all)
      
      @new_users.each_index do |key|
        @user = @new_users[key]
        @old_user = @old_users[key]
        
        @user.password = @user.password_confirmation = @old_user.attributes["password"]
        @user.salt = @user.send(:create_salt)
        #@user.save!
        @user.save_without_validation
      end
      
    rescue Exception => msg
      
      self.remove_generator_password #alter, drop, create doet hij niet als rollback
      raise Exception, msg
    end
    
    remove_column :users, :password
  end

  def self.down
    self.remove_generator_password
    add_column 'users', :password, :string, :null => false
    
    User.update_all "password = 'testtest'"
    
  end
  
  def self.remove_generator_password
    remove_column :users, :crypted_password
    remove_column :users, :salt
  end
end
